package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.AiModelConfig;
import com.yfp.operation.domain.AiModelService;
import com.yfp.operation.domain.dto.AiModelServiceInfoDTO;
import com.yfp.operation.domain.dto.SiliconFlowRetrieveAccountInformationDTO;
import com.yfp.operation.domain.dto.SiliconFlowRetrieveModelsInformationDTO;
import com.yfp.operation.domain.vo.AiModelConfigVO;
import com.yfp.operation.domain.vo.AiModelServiceInfoVO;
import com.yfp.operation.mapper.AiModelServiceMapper;
import com.yfp.operation.service.AiModelConfigService;
import com.yfp.operation.service.AiModelServiceService;
import com.yfp.operation.service.SiliconFlowService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 *
 * @description 针对表【ai_model_service(AI模型服务表)】的数据库操作Service实现
 * @createDate 2025-02-24 15:08:52
 */
@Service
public class AiModelServiceServiceImpl extends ServiceImpl<AiModelServiceMapper, AiModelService> implements AiModelServiceService {

    @Resource
    private SiliconFlowService siliconFlowService;
    @Resource
    private AiModelServiceMapper aiModelServiceMapper;
    @Resource
    private AiModelConfigService aiModelConfigService;

    @Override
    public AiModelServiceInfoVO getInfoByType(String type) {

        AiModelService aiModelService = aiModelServiceMapper.selectByType(type);
        if (Objects.isNull(aiModelService)) {
            return null;
        }
        AiModelServiceInfoVO aiModelServiceVO = BeanUtil.toBean(aiModelService, AiModelServiceInfoVO.class);

        List<AiModelConfig> aiModelConfigs = aiModelConfigService.listByModelServiceId(aiModelService.getId());
        List<AiModelConfigVO> aiModelConfigVO = BeanUtil.copyToList(aiModelConfigs, AiModelConfigVO.class);
        aiModelServiceVO.setAiModelConfigs(aiModelConfigVO);

        return aiModelServiceVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateModelServiceInfo(AiModelServiceInfoDTO aiModelServiceInfoDTO) {

        aiModelServiceInfoDTO.setType("silicon-flow");
        AiModelService aiModelServiceOld = aiModelServiceMapper.selectByType("silicon-flow");

        if (Objects.isNull(aiModelServiceOld)) {
            // 为空 新增
            this.saveModelServiceInfo(aiModelServiceInfoDTO);
        } else {
            // 不为空 更新
            aiModelServiceInfoDTO.setId(aiModelServiceOld.getId());
            this.updateModelServiceInfo(aiModelServiceInfoDTO);
        }
    }

    @Override
    public void saveModelServiceInfo(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        AiModelService aiModelService = BeanUtil.toBean(aiModelServiceInfoDTO, AiModelService.class);

        aiModelService.setCreateTime(date);
        aiModelService.setCreateUserId(userId);
        aiModelService.setUpdateTime(date);
        aiModelService.setUpdateUserId(userId);
        aiModelServiceMapper.insert(aiModelService);

        List<AiModelConfig> aiModelConfigs = BeanUtil.copyToList(aiModelServiceInfoDTO.getAiModelConfigs(), AiModelConfig.class);
        aiModelConfigs.forEach(item -> {
            item.setCreateTime(date);
            item.setCreateUserId(userId);
            item.setUpdateTime(date);
            item.setUpdateUserId(userId);

            item.setAiModelServiceId(aiModelService.getId());
        });
        aiModelConfigService.saveBatch(aiModelConfigs);
    }

    @Override
    public void updateModelServiceInfo(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();
        AiModelService aiModelService = BeanUtil.toBean(aiModelServiceInfoDTO, AiModelService.class);

        aiModelService.setUpdateTime(date);
        aiModelService.setUpdateUserId(userId);
        aiModelServiceMapper.updateByType(aiModelService);

        aiModelConfigService.removeByModelServiceId(aiModelService.getId());
        List<AiModelConfig> aiModelConfigs = BeanUtil.copyToList(aiModelServiceInfoDTO.getAiModelConfigs(), AiModelConfig.class);
        aiModelConfigs.forEach(item -> {
            item.setCreateTime(date);
            item.setCreateUserId(userId);
            item.setUpdateTime(date);
            item.setUpdateUserId(userId);

            item.setAiModelServiceId(aiModelService.getId());
        });
        aiModelConfigService.saveBatch(aiModelConfigs);
    }

    @Override
    public void checkModelServiceInfoBySiliconFlow(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        Assert.notBlank(aiModelServiceInfoDTO.getApiUrl(), "API 地址不能为空");
        Assert.notBlank(aiModelServiceInfoDTO.getApiKey(), "API 密钥不能为空");
        Assert.notBlank(CollUtil.getFirst(aiModelServiceInfoDTO.getAiModelConfigs()).getName(), "请选择要检测的模型");

        aiModelServiceInfoDTO.setType("silicon-flow");
        // 目前只对接 silicon-flow 硅基流动
        if (StrUtil.equals(aiModelServiceInfoDTO.getType(), "silicon-flow")) {
            // 获取账户信息
            SiliconFlowRetrieveAccountInformationDTO retrieveAccountInformationDTO = siliconFlowService.retrieveAccountInformation(aiModelServiceInfoDTO);
            if (!retrieveAccountInformationDTO.getStatus()) {
                throw new ServiceException(retrieveAccountInformationDTO.getMessage());
            }

            // 获取模型信息
            SiliconFlowRetrieveModelsInformationDTO retrieveModelsInformationDTO = siliconFlowService.retrieveModelsInformation(aiModelServiceInfoDTO);
            long count = retrieveModelsInformationDTO.getData().stream().filter(item -> {
                return StrUtil.equals(item.getId(), CollUtil.getFirst(aiModelServiceInfoDTO.getAiModelConfigs()).getName());
            }).count();
            if (count == 0) {
                throw new ServiceException("模型不存在:" + CollUtil.getFirst(aiModelServiceInfoDTO.getAiModelConfigs()).getName());
            }
        }
    }
}




